package com.school.manager.config;

import java.io.File;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import com.school.manager.filter.LoginInterceptor;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;

/**
 * description：web拦截器
 * date：2021/10/221:44 下午
 */

@Configuration
public class MyWebIntercept implements WebMvcConfigurer {
	
	@Value("${file.upload.path}")
	private String preUrl;
	
	@Autowired
	private ResourceLoader resourceLoader;
	
	@Value("${system.super.admin}")
	private String superAdmin;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        ThreadUtil.execute(()->this.initSuperAdmin());
        	String filePattern = "file:" + preUrl;
        registry.addResourceHandler("/photo/**").addResourceLocations(
        		filePattern);
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/", "classpath:/mappers/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    	registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**")
    	.excludePathPatterns("/**/*.html", "/**/login", "/**/register", "/**/css/**", "/**/photo/**", "/webjars/**", "/**/js/**", "/**/img/**", "/**/fonts/**","/**/*.ico");
    }
    
    private void initSuperAdmin() {
    	FileUtil.mkdir(preUrl);
    	Resource resource = resourceLoader.getResource("classpath:/photo/superadmin.jpeg");
    	try {
    		String copyPayh = new StringBuilder(preUrl).append(superAdmin).append(StrUtil.DOT).append("jpeg").toString();
    		File copyFile = new File(copyPayh);
    		// 文件不存在复制
    		if (!FileUtil.exist(copyFile)) {
    			FileUtil.copy(resource.getFile(), copyFile, false);
			}
		} catch (IORuntimeException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
}
